package com.zxy.supplier_system.server.entity.embeddable

import com.zxy.supplier_system.server.entity.Goods
import com.zxy.supplier_system.server.entity.GoodsBrand
import com.zxy.supplier_system.server.entity.GoodsBrandTag
import com.zxy.supplier_system.server.entity.GoodsCategory
import com.zxy.supplier_system.server.utils.orElse404
import jakarta.persistence.CascadeType
import jakarta.persistence.Embeddable
import jakarta.persistence.FetchType
import jakarta.persistence.ManyToMany

@Embeddable
class GoodsMatcherRule {

    @ManyToMany(fetch = FetchType.LAZY, cascade = [CascadeType.DETACH])
    var includedBrands: MutableList<GoodsBrand> = mutableListOf()

    @ManyToMany(fetch = FetchType.LAZY, cascade = [CascadeType.DETACH])
    var includedCategories: MutableList<GoodsCategory> = mutableListOf()

    @ManyToMany(fetch = FetchType.LAZY, cascade = [CascadeType.DETACH])
    var includedBrandTags: MutableList<GoodsBrandTag> = mutableListOf()

    @ManyToMany(fetch = FetchType.LAZY, cascade = [CascadeType.DETACH])
    var includedGoodsList: MutableList<Goods> = mutableListOf()

    val hasScope: Boolean
        get() {
            return includedBrands.isNotEmpty() || includedCategories.isNotEmpty() || this.includedBrandTags.isNotEmpty() || this.includedGoodsList.isNotEmpty()
        }

    fun goodsInScope(goods: Goods): Boolean {
        return (this.includedBrands.isEmpty() || this.includedBrands.contains(goods.brand))
                && (this.includedCategories.isEmpty() || this.includedCategories.contains(goods.category))
                && (this.includedGoodsList.isEmpty() || this.includedGoodsList.contains(goods))
                && (this.includedBrandTags.isEmpty() || this.includedBrandTags.any { brandTag ->
            goods.brand?.tags?.contains(
                brandTag
            ) ?: false
        })
    }

}

interface GoodsMatcherRuleRequestStruct{
    val includedBrandIds: List<Int>
    val includedCategoryIds: List<Int>
    val includedBrandTagIds: List<Int>
    val includedGoodsIds: List<Int>
}